<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Websocket Demo -- Chat</title>
<style type="text/css">
        input#chat {
            width: 410px
        }
        #console-container {
            width: 400px;
        }
        #console {
            border: 1px solid #CCCCCC;
            border-right-color: #999999;
            border-bottom-color: #999999;
            height: 170px;
            overflow-y: scroll;
            padding: 5px;
            width: 100%;
        }
        #console p {
            padding: 0;
            margin: 0;
        }
	</style>
    <script type="application/javascript">
 		// 初始化一个 WebSocket 对象
		var ws = null;
		
 		login = function(){
 			var loginName = document.getElementById("loginName").value;
 			
 			var domain = window.location.host;
 			//alert(domain);
 			ws = new WebSocket("ws://localhost:18082/websocket/chat/"+loginName);
 			//ws = new WebSocket("ws://localhost:8080/websocket");
 			
 			// 建立 web socket 连接成功触发事件
 		    ws.onopen = function () {
 		      // 使用 send() 方法发送数据
			 document.getElementById('chat').onkeydown = function(event) {
                 if (event.keyCode == 13) {
                     sendMessage();
                 }
             }
 		    };
 		
 		    // 接收服务端数据时触发事件
 		    ws.onmessage = function (evt) {
 		      var received_msg = evt.data;
 		      log(received_msg);
 		    };
 		
 		    // 断开 web socket 连接成功触发事件
 		    ws.onclose = function () {
 		    	document.getElementById('chat').onkeydown = null;
                log('Info: WebSocket 关闭.');
 		    };
			
			ws.onerror = function () {
			    log('Info: WebSocket 出错.');
			};
 		};
		
		sendMessage = function() {
		    var message = document.getElementById('chat').value;
		    if (message != '') {
		    	ws.send(message);
		        document.getElementById('chat').value = '';
		    }
		};
		
		log = function(message) {
		    var console = document.getElementById('console');
		    var p = document.createElement('p');
		    p.style.wordWrap = 'break-word';
		    p.innerHTML = message;
		    console.appendChild(p);
		    while (console.childNodes.length > 25) {
		        console.removeChild(console.firstChild);
		    }
		    console.scrollTop = console.scrollHeight;
		};
		
		close_ws = function(){
			//debugger
			alert("close");
			ws.close();
		};
    </script>
</head>
<body>
	<div>
		<p>
	        <input type="text" placeholder="请输入你的名字" id="loginName" />
	        <input type="button" value="Login" onclick="login()">
			<input type="button" value="Close" onclick="close_ws()">
	    </p>
	    <p>
	        <input type="text" placeholder="请输入..." id="chat" />
	    </p>
	    <div id="console-container">
	        <div id="console"/>
	    </div>
	</div>
        
</body>
</html>
